package com.coder.bike.security;

import com.coder.bike.entity.Customer;
import com.coder.bike.entity.Permission;
import com.coder.bike.entity.Staff;
import com.coder.bike.security.AuthUser;
import com.coder.bike.service.ICustomerService;
import com.coder.bike.service.IPermissionService;
import com.coder.bike.service.IStaffService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class CustomerUserDetailsService implements UserDetailsService {
    @Resource
    private IStaffService staffService;
    @Resource
    private ICustomerService customerService;
    @Resource
    private IPermissionService permissionService;

    // 添加日志记录
    private static final Logger log = LoggerFactory.getLogger(CustomerUserDetailsService.class);

    public UserDetails loadUserByPhone(String phone) {
        log.debug("开始通过手机号查询用户: {}", phone);

        // 先查客户表
        Customer customer = customerService.selectByPhone(phone);
        if (customer != null) {
            log.debug("找到客户用户: {}", customer.getUsername());
            return AuthUser.fromCustomer(customer);
        }

        // 再查员工表
        Staff staff = staffService.selectByPhone(phone);
        if (staff != null) {
            // 获取员工权限
            List<Permission> permissions = permissionService.selectPermissionListByStaffId(staff.getId());
            staff.setPermissionList(permissions);
            log.debug("找到员工用户: {}", staff.getUsername());
            return AuthUser.fromStaff(staff);
        }

        log.warn("未找到手机号 {} 对应的用户", phone);
        throw new UsernameNotFoundException("该手机号未注册");
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("通过用户名查询用户: {}", username);

        // 先检查是否是手机号格式
        if (username.matches("^1[3-9]\\d{9}$")) {
            log.debug("用户名是手机号格式，尝试通过手机号查询");
            return loadUserByPhone(username);
        }

        // 原有用户名查询逻辑
        Staff staff = staffService.selectByUsername(username);
        Customer customer = customerService.selectByUsername(username);

        if (staff != null) {
            List<Permission> permissions = permissionService.selectPermissionListByStaffId(staff.getId());
            staff.setPermissionList(permissions);
            return AuthUser.fromStaff(staff);
        } else if (customer != null) {
            return AuthUser.fromCustomer(customer);
        }

        throw new UsernameNotFoundException("用户不存在");
    }
}